#include<stdio.h>
#include <stdlib.h>
#include<syslog.h>
#include<arpa/inet.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<errno.h>
#include<signal.h>
#include<unistd.h>

int flag = 0;
static char *sock_ntop_host(const struct sockaddr_in *sa, int len)
{
	static char str[128];
	if(sa->sin_family == AF_INET)
	{
		if(inet_ntop(AF_INET, &sa->sin_addr, str, sizeof(str)) == NULL)
		{
			return(NULL);
			perror("inet_ntop");
			exit(1);
		}
		return(str);
	}
	exit(1);

}
	
static void recvfrom_alarm(int signo)
{
 
	flag = 1;
	return;
}

int main(int arg, char **argv)
{

	int sockfd;
	struct sockaddr_in sendaddr, localaddr, cliaddr;
	int i;
	char buff[] = {'q','l','i','z','h','i'};
	int len = sizeof(buff);
	const int on = 1;
	char recvbuff[1024];
	int fromlen;
	int n;

	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	if(sockfd < 0)
	{
		perror("socket error");
		exit(1);

	}
	i = setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on));
	if (i < 0)
	{
		perror("setsockopt error");
		exit(1);
	}
	bzero(&localaddr, sizeof(localaddr));
	localaddr.sin_family = AF_INET;
	localaddr.sin_port = htons(8081);
	i = bind (sockfd, (struct sockaddr *)&localaddr, sizeof(localaddr));
	if(i < 0)
	{
		perror("bind error");
		exit(1);
	}


	//============================================
	bzero(&sendaddr, sizeof(sendaddr));
	sendaddr.sin_family = AF_INET;
	sendaddr.sin_port = htons(8080);
	i = inet_pton(AF_INET, argv[1], &sendaddr.sin_addr);
	if(i == 0)
	{
		perror("argv[1]  error");
		exit(1);
	}else if(i == -1)
	{
		perror("inet_pton error");
		exit(1);
	}
        //=============================================
	
	while(1){
		flag = 0;
		/* send   */
		i = sendto(sockfd, buff, len, 0,(struct sockaddr *)&sendaddr, sizeof(sendaddr));
		if (i < 0)
		{
			perror("sendto error");
			exit(1);
		}

		/*receive host*/
		signal(SIGALRM, recvfrom_alarm);
		alarm(5);

		while(flag == 0)
		{
			n = recvfrom(sockfd, recvbuff, 1023, 0, (struct sockaddr *)&cliaddr, &fromlen);
			if (n < 0)
			{
				if(errno == EINTR)
					break;
				else
				{
					perror("recvfrom error");
					exit(1);
				}

			}else
			{
				recvbuff[n] = '\0';
				printf("%s\n",recvbuff);
				if(strcmp(recvbuff, "yong") == 0)
				{
				  	printf("from %s :%s\n", sock_ntop_host(&cliaddr,sizeof(cliaddr)), recvbuff);
				}
			}

		} //while

		sleep(5);
	}


	return 0;
}
